#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
日报生成器
自动扫描指定目录下的所有Git仓库，提取指定用户在指定月份的提交信息，
并通过AI模型生成日报。
"""

import argparse
import os
import sys
from collections import defaultdict
from dataclasses import dataclass
from datetime import datetime
from pathlib import Path
from typing import List, Dict, Optional

import git
from loguru import logger


@dataclass
class ProjectInfo:
    """项目信息数据类"""
    name: str
    path: Path
    description: str
    domain: str  # 领域：hydrology, geoscience, ai, iot, etc.
    technologies: List[str]
    recent_focus: str


@dataclass
class CommitInfo:
    """提交信息数据类"""
    repo_name: str
    commit_hash: str
    message: str
    date: datetime
    files_changed: List[str]
    insertions: int
    deletions: int
    author_name: str
    author_email: str


class ProjectDocumentAnalyzer:
    """项目文档分析器"""

    def __init__(self, source_dir: str):
        self.source_dir = Path(source_dir)
        self.domain_keywords = {
            'hydrology': ['水文', '水利', '流域', '降雨', '径流', '洪水', '水资源', 'hydrology', 'watershed',
                          'rainfall', 'runoff', 'flood'],
            'geoscience': ['地学', '地质', '地理', '遥感', '地信', 'GIS', 'RS', 'geology', 'geography',
                           'remote sensing', 'geospatial'],
            'ai': ['人工智能', '机器学习', '深度学习', '大模型', 'AI', 'ML', 'DL', 'LLM', 'neural', 'transformer',
                   'pytorch', 'tensorflow'],
            'iot': ['物联网', '传感器', '嵌入式', 'IoT', 'sensor', 'embedded', 'arduino', 'raspberry', 'mqtt', 'zigbee']
        }

    def analyze_project_documents(self, repo_path: Path) -> ProjectInfo:
        """分析项目文档，提取项目信息"""
        project_name = repo_path.name

        # 查找项目文档
        doc_files = self._find_project_docs(repo_path)

        # 分析文档内容
        description = self._extract_description(doc_files)
        domain = self._identify_domain(doc_files, description)
        technologies = self._extract_technologies(doc_files, repo_path)
        recent_focus = self._analyze_recent_focus(doc_files)

        return ProjectInfo(
            name=project_name,
            path=repo_path,
            description=description,
            domain=domain,
            technologies=technologies,
            recent_focus=recent_focus
        )

    def _find_project_docs(self, repo_path: Path) -> List[Path]:
        """查找项目相关文档"""
        doc_patterns = [
            'README.md', 'README.rst', 'README.txt',
            'docs/*.md', 'doc/*.md', 'documentation/*.md',
            '*.md', 'CHANGELOG.md', 'HISTORY.md',
            'requirements.txt', 'pyproject.toml', 'package.json',
            'Dockerfile', 'docker-compose.yml'
        ]

        doc_files = []
        for pattern in doc_patterns:
            files = list(repo_path.glob(pattern))
            doc_files.extend(files)

        return doc_files[:10]  # 限制文档数量，避免过多

    def _extract_description(self, doc_files: List[Path]) -> str:
        """从文档中提取项目描述"""
        description = ""

        # 优先从README文件提取
        readme_files = [f for f in doc_files if 'readme' in f.name.lower()]
        if readme_files:
            try:
                content = readme_files[0].read_text(encoding='utf-8', errors='ignore')
                # 提取第一段或标题下的内容
                lines = content.split('\n')
                for i, line in enumerate(lines):
                    if line.strip() and not line.startswith('#'):
                        # 找到第一个非标题行，提取接下来几行作为描述
                        desc_lines = []
                        for j in range(i, min(i + 5, len(lines))):
                            if lines[j].strip() and not lines[j].startswith('#'):
                                desc_lines.append(lines[j].strip())
                        description = ' '.join(desc_lines)[:200]
                        break
            except Exception as e:
                logger.debug(f"读取README文件失败: {e}")

        return description or "研发项目"

    def _identify_domain(self, doc_files: List[Path], description: str) -> str:
        """识别项目领域"""
        text_content = description.lower()

        # 从文档文件中提取更多文本
        for doc_file in doc_files[:3]:  # 只分析前3个文档
            try:
                content = doc_file.read_text(encoding='utf-8', errors='ignore')
                text_content += ' ' + content[:1000].lower()  # 只取前1000字符
            except Exception:
                continue

        # 统计各领域关键词出现次数
        domain_scores = {}
        for domain, keywords in self.domain_keywords.items():
            score = sum(text_content.count(keyword.lower()) for keyword in keywords)
            domain_scores[domain] = score

        # 返回得分最高的领域
        if domain_scores:
            best_domain = max(domain_scores, key=domain_scores.get)
            if domain_scores[best_domain] > 0:
                return best_domain

        return 'general'

    def _extract_technologies(self, doc_files: List[Path], repo_path: Path) -> List[str]:
        """提取项目使用的技术栈"""
        technologies = set()

        # 从文件扩展名推断技术栈
        code_files = list(repo_path.rglob('*'))[:50]  # 限制文件数量
        for file_path in code_files:
            if file_path.is_file():
                ext = file_path.suffix.lower()
                if ext == '.py':
                    technologies.add('Python')
                elif ext in ['.js', '.ts']:
                    technologies.add('JavaScript/TypeScript')
                elif ext == '.vue':
                    technologies.add('Vue.js')
                elif ext in ['.java']:
                    technologies.add('Java')
                elif ext in ['.cpp', '.c', '.h']:
                    technologies.add('C/C++')
                elif ext in ['.go']:
                    technologies.add('Go')
                elif ext in ['.rs']:
                    technologies.add('Rust')

        # 从配置文件推断框架
        for doc_file in doc_files:
            try:
                content = doc_file.read_text(encoding='utf-8', errors='ignore').lower()
                if 'requirements.txt' in doc_file.name or 'pyproject.toml' in doc_file.name:
                    if 'django' in content:
                        technologies.add('Django')
                    if 'flask' in content:
                        technologies.add('Flask')
                    if 'pytorch' in content:
                        technologies.add('PyTorch')
                    if 'tensorflow' in content:
                        technologies.add('TensorFlow')
                elif 'package.json' in doc_file.name:
                    if 'react' in content:
                        technologies.add('React')
                    if 'vue' in content:
                        technologies.add('Vue')
                elif 'dockerfile' in doc_file.name.lower():
                    technologies.add('Docker')
            except Exception:
                continue

        return list(technologies)[:5]  # 限制技术栈数量

    def _analyze_recent_focus(self, doc_files: List[Path]) -> str:
        """分析项目近期关注点"""
        # 查找CHANGELOG或最近的文档更新
        changelog_files = [f for f in doc_files if 'changelog' in f.name.lower() or 'history' in f.name.lower()]

        if changelog_files:
            try:
                content = changelog_files[0].read_text(encoding='utf-8', errors='ignore')
                # 提取最近的更新内容
                lines = content.split('\n')[:20]  # 只看前20行
                recent_content = ' '.join(lines)
                if len(recent_content) > 100:
                    return recent_content[:100] + "..."
            except Exception:
                pass

        return "持续开发中"


class GitRepoScanner:
    """Git仓库扫描器"""

    def __init__(self, source_dir: str):
        self.source_dir = Path(source_dir)
        if not self.source_dir.exists():
            raise ValueError(f"源目录不存在: {source_dir}")

    def find_git_repos(self) -> List[Path]:
        """查找所有Git仓库"""
        git_repos = []

        logger.info(f"开始扫描目录: {self.source_dir}")

        for root, dirs, files in os.walk(self.source_dir):
            # 检查是否包含.git目录
            if '.git' in dirs:
                repo_path = Path(root)
                git_repos.append(repo_path)
                logger.debug(f"发现Git仓库: {repo_path}")

            # 跳过隐藏目录和常见的非项目目录，但要在检查.git之后
            dirs[:] = [d for d in dirs if
                       not d.startswith('.') and d not in ['node_modules', '__pycache__', 'venv', 'env']]

        logger.info(f"总共发现 {len(git_repos)} 个Git仓库")
        return git_repos

    def get_commits_for_user_and_month(self, repo_path: Path, user_id: str, year: int, month: int) -> List[CommitInfo]:
        """获取指定用户在指定月份的提交信息"""
        commits = []

        try:
            repo = git.Repo(repo_path)

            # 计算月份的开始和结束日期
            start_date = datetime(year, month, 1)
            if month == 12:
                end_date = datetime(year + 1, 1, 1)
            else:
                end_date = datetime(year, month + 1, 1)

            # 获取指定时间范围内的提交
            commits_iter = repo.iter_commits(
                since=start_date,
                until=end_date,
                author=user_id
            )

            for commit in commits_iter:
                try:
                    # 获取文件变更统计
                    stats = commit.stats
                    files_changed = list(stats.files.keys())
                    insertions = stats.total['insertions']
                    deletions = stats.total['deletions']

                    commit_info = CommitInfo(
                        repo_name=repo_path.name,
                        commit_hash=commit.hexsha[:8],
                        message=commit.message.strip(),
                        date=datetime.fromtimestamp(commit.committed_date),
                        files_changed=files_changed,
                        insertions=insertions,
                        deletions=deletions,
                        author_name=commit.author.name,
                        author_email=commit.author.email
                    )
                    commits.append(commit_info)

                except Exception as e:
                    logger.warning(f"处理提交 {commit.hexsha[:8]} 时出错: {e}")
                    continue

        except Exception as e:
            logger.error(f"处理仓库 {repo_path} 时出错: {e}")

        return commits


class DailyReportGenerator:
    """日报生成器"""

    def __init__(self, source_dir: str, user_id: str):
        self.scanner = GitRepoScanner(source_dir)
        self.doc_analyzer = ProjectDocumentAnalyzer(source_dir)
        self.user_id = user_id
        self.project_cache = {}  # 缓存项目信息

    def get_project_info(self, repo_path: Path) -> ProjectInfo:
        """获取项目信息（带缓存）"""
        repo_key = str(repo_path)
        if repo_key not in self.project_cache:
            self.project_cache[repo_key] = self.doc_analyzer.analyze_project_documents(repo_path)
        return self.project_cache[repo_key]

    def collect_monthly_commits(self, year: int, month: int) -> Dict[int, List[CommitInfo]]:
        """收集指定月份的所有提交，按日期分组"""
        git_repos = self.scanner.find_git_repos()
        daily_commits = defaultdict(list)

        logger.info(f"开始收集 {year}年{month}月 用户 {self.user_id} 的提交信息")

        for repo_path in git_repos:
            commits = self.scanner.get_commits_for_user_and_month(repo_path, self.user_id, year, month)

            for commit in commits:
                day = commit.date.day
                daily_commits[day].append(commit)

        # 按日期排序
        for day in daily_commits:
            daily_commits[day].sort(key=lambda x: x.date)

        logger.info(f"收集完成，共 {len(daily_commits)} 天有提交记录")
        return dict(daily_commits)

    def _extract_work_summary(self, commit_message: str, repo_name: str,
                              project_info: Optional[ProjectInfo] = None) -> str:
        """提取工作内容摘要（增强研发特征识别）"""
        # 清理commit message，提取主要内容
        message = commit_message.split('\n')[0]  # 取第一行

        # 移除常见的前缀，但保留重要的研发标识
        research_prefixes = {
            'feat:': '功能开发',
            'fix:': '问题修复',
            'docs:': '文档更新',
            'refactor:': '代码重构',
            'perf:': '性能优化',
            'test:': '测试完善',
            'experiment:': '实验研究',
            'model:': '模型开发',
            'data:': '数据处理',
            'analysis:': '分析研究'
        }

        work_type = ""
        for prefix, work_desc in research_prefixes.items():
            if message.lower().startswith(prefix):
                work_type = f"[{work_desc}] "
                message = message[len(prefix):].strip()
                break

        # 根据项目领域增强描述
        if project_info:
            domain_context = {
                'hydrology': '水文',
                'geoscience': '地学',
                'ai': 'AI',
                'iot': '物联网'
            }
            if project_info.domain in domain_context:
                work_type = f"[{domain_context[project_info.domain]}] " + work_type

        # 识别研发关键词并增强描述
        research_keywords = {
            '算法': '算法研究', '模型': '模型开发', '数据': '数据分析',
            '实验': '实验验证', '优化': '性能优化', '测试': '功能测试',
            '分析': '技术分析', '设计': '系统设计', '接口': '接口开发',
            'api': 'API开发', 'model': '模型', 'algorithm': '算法',
            'optimization': '优化', 'analysis': '分析'
        }

        message_lower = message.lower()
        for keyword, enhanced in research_keywords.items():
            if keyword in message_lower and enhanced not in message:
                # 如果消息中包含关键词但没有增强描述，则添加
                break

        # 截断过长的消息
        full_message = work_type + message
        if len(full_message) > 60:
            full_message = full_message[:57] + "..."

        return full_message or "代码更新"

    def _infer_daily_tasks_from_commits(self, commits: List[CommitInfo]) -> List[str]:
        """从提交记录推断每日任务"""
        tasks = []

        # 按项目分组
        repo_commits = defaultdict(list)
        for commit in commits:
            repo_commits[commit.repo_name].append(commit)

        for repo_name, repo_commits_list in repo_commits.items():
            # 获取项目信息
            repo_path = None
            for commit in repo_commits_list:
                # 尝试从scanner中获取repo路径
                git_repos = self.scanner.find_git_repos()
                for git_repo in git_repos:
                    if git_repo.name == repo_name:
                        repo_path = git_repo
                        break
                if repo_path:
                    break

            project_info = None
            if repo_path:
                project_info = self.get_project_info(repo_path)

            # 分析提交类型和文件变更
            file_types = defaultdict(int)
            commit_types = defaultdict(int)

            for commit in repo_commits_list:
                # 统计文件类型
                for file_path in commit.files_changed:
                    ext = Path(file_path).suffix.lower()
                    if ext:
                        file_types[ext] += 1

                # 统计提交类型
                message = commit.message.lower()
                if any(word in message for word in ['fix', 'bug', '修复', '错误']):
                    commit_types['bug_fix'] += 1
                elif any(word in message for word in ['feat', 'add', '新增', '功能']):
                    commit_types['feature'] += 1
                elif any(word in message for word in ['doc', '文档', 'readme']):
                    commit_types['documentation'] += 1
                elif any(word in message for word in ['test', '测试']):
                    commit_types['testing'] += 1
                elif any(word in message for word in ['refactor', '重构', '优化']):
                    commit_types['refactor'] += 1
                else:
                    commit_types['development'] += 1

            # 生成任务描述
            task_parts = []

            # 添加项目背景 - 简化描述，不重复强调项目类型
            task_parts.append(f"{repo_name}")

            # 添加主要工作类型
            main_work = max(commit_types.items(), key=lambda x: x[1])
            work_desc = {
                'feature': '功能开发',
                'bug_fix': '问题修复',
                'documentation': '文档完善',
                'testing': '测试验证',
                'refactor': '代码优化',
                'development': '开发工作'
            }.get(main_work[0], '开发工作')

            task_parts.append(work_desc)

            # 添加技术细节
            if file_types:
                main_file_type = max(file_types.items(), key=lambda x: x[1])
                tech_desc = {
                    '.py': 'Python开发',
                    '.js': 'JavaScript开发',
                    '.ts': 'TypeScript开发',
                    '.java': 'Java开发',
                    '.cpp': 'C++开发',
                    '.c': 'C开发',
                    '.go': 'Go开发',
                    '.md': '文档编写',
                    '.yml': '配置管理',
                    '.json': '配置调整'
                }.get(main_file_type[0], '代码开发')
                task_parts.append(tech_desc)

            # 添加工作量描述
            total_changes = sum(c.insertions + c.deletions for c in repo_commits_list)
            if total_changes > 500:
                task_parts.append('大量代码变更')
            elif total_changes > 100:
                task_parts.append('中等规模开发')
            else:
                task_parts.append('小幅调整优化')

            tasks.append('，'.join(task_parts))

        return tasks

    def format_daily_work_summary(self, day: int, commits: List[CommitInfo], year: int, month: int) -> str:
        """格式化单日工作总结，包含详细的技术分析"""
        if not commits:
            return f"## {year}年{month}月{day}日\n\n无工作记录\n"

        date_str = f"{year}年{month}月{day}日"
        total_commits = len(commits)
        total_insertions = sum(c.insertions for c in commits)
        total_deletions = sum(c.deletions for c in commits)
        repo_count = len(set(c.repo_name for c in commits))

        # 推断每日任务
        daily_tasks = self._infer_daily_tasks_from_commits(commits)

        # 按项目分组统计
        repo_stats = defaultdict(list)
        for commit in commits:
            repo_stats[commit.repo_name].append(commit)

        # 技术栈和文件类型分析
        all_file_types = defaultdict(int)
        all_changed_files = []
        for commit in commits:
            all_changed_files.extend(commit.files_changed)
            for file_path in commit.files_changed:
                if '.' in file_path:
                    ext = file_path.split('.')[-1].lower()
                    all_file_types[ext] += 1

        # 生成报告内容
        report_lines = [
            f"## {date_str} 研发工作总结",
            "",
            f"**工作统计：** {total_commits}次提交，{repo_count}个项目，代码变更 +{total_insertions}/-{total_deletions} 行",
            ""
        ]

        # 技术栈分析
        if all_file_types:
            report_lines.append("**技术栈分析：**")
            sorted_file_types = sorted(all_file_types.items(), key=lambda x: x[1], reverse=True)
            tech_analysis = []
            for ext, count in sorted_file_types[:5]:  # 显示前5种文件类型
                percentage = (count / len(all_changed_files)) * 100
                tech_analysis.append(f"{ext}文件({count}处变更，占{percentage:.1f}%)")
            report_lines.append("- " + "、".join(tech_analysis))
            report_lines.append("")

        # 添加推断的主要任务
        if daily_tasks:
            report_lines.append("**主要工作内容：**")
            for i, task in enumerate(daily_tasks[:3], 1):  # 最多显示3个主要任务
                report_lines.append(f"{i}. {task}")
            report_lines.append("")

        # 按项目详细列出技术工作
        report_lines.append("**技术工作详情：**")
        for repo_name, repo_commits in repo_stats.items():
            commit_count = len(repo_commits)
            repo_insertions = sum(c.insertions for c in repo_commits)
            repo_deletions = sum(c.deletions for c in repo_commits)

            # 获取项目信息
            repo_path = None
            git_repos = self.scanner.find_git_repos()
            for git_repo in git_repos:
                if git_repo.name == repo_name:
                    repo_path = git_repo
                    break

            project_info = None
            if repo_path:
                project_info = self.get_project_info(repo_path)

            # 项目标题 - 移除项目类型强调
            project_title = f"**{repo_name}** - {commit_count}次提交，+{repo_insertions}/-{repo_deletions}行"
            report_lines.append(project_title)

            # 项目级别的文件类型分析
            project_file_types = defaultdict(int)
            for commit in repo_commits:
                for file_path in commit.files_changed:
                    if '.' in file_path:
                        ext = file_path.split('.')[-1].lower()
                        project_file_types[ext] += 1
            
            if project_file_types:
                main_types = sorted(project_file_types.items(), key=lambda x: x[1], reverse=True)[:3]
                type_desc = "，".join([f"{ext}({count})" for ext, count in main_types])
                report_lines.append(f"  *涉及文件类型：{type_desc}*")

            # 生成详细的工作总结
            work_summary = self._generate_work_summary(repo_commits, project_info)
            # 将总结按行分割并添加适当的缩进
            summary_lines = work_summary.split('\n')
            for line in summary_lines:
                if line.strip():
                    report_lines.append(f"  {line}")
            report_lines.append("")

        # 添加整体技术影响分析
        if total_insertions > 500 or len(all_changed_files) > 20:
            report_lines.append("**技术影响评估：**")
            if total_insertions > 1000:
                report_lines.append(f"- 大规模代码变更：新增{total_insertions}行代码，体现了重要功能开发或架构调整")
            elif total_insertions > 500:
                report_lines.append(f"- 中等规模开发：{total_insertions}行新增代码，推进了项目核心功能")
            
            if len(all_changed_files) > 50:
                report_lines.append(f"- 广泛影响范围：涉及{len(all_changed_files)}个文件的修改，体现了系统性的改进")
            elif len(all_changed_files) > 20:
                report_lines.append(f"- 多文件协调：{len(all_changed_files)}个文件的变更，展现了良好的代码组织")
            
            # 代码质量指标
            if total_deletions > 0:
                change_ratio = total_deletions / (total_insertions + total_deletions)
                if change_ratio > 0.3:
                    report_lines.append(f"- 代码重构优化：删除{total_deletions}行代码，优化了代码结构和质量")
                else:
                    report_lines.append(f"- 功能扩展为主：以新增功能为主，删除{total_deletions}行冗余代码")
            
            report_lines.append("")

        return "\n".join(report_lines)

    def _generate_work_summary(self, commits: List[CommitInfo], project_info: Optional[ProjectInfo] = None) -> str:
        """生成详细的工作总结（至少300字）"""
        if not commits:
            return "无工作记录"
        
        # 分析工作类型和详细内容
        work_types = defaultdict(int)
        features = []
        fixes = []
        docs = []
        tests = []
        refactors = []
        others = []
        
        # 统计文件类型和变更
        file_types = defaultdict(int)
        total_insertions = sum(c.insertions for c in commits)
        total_deletions = sum(c.deletions for c in commits)
        
        for commit in commits:
            msg = commit.message.lower()
            
            # 统计文件类型
            for file_path in commit.files_changed:
                if '.' in file_path:
                    ext = file_path.split('.')[-1].lower()
                    file_types[ext] += 1
            
            # 分类commit
            if any(keyword in msg for keyword in ['feat', 'feature', '功能', '新增', '添加']):
                work_types['feature'] += 1
                features.append(commit.message)
            elif any(keyword in msg for keyword in ['fix', 'bug', '修复', '问题']):
                work_types['fix'] += 1
                fixes.append(commit.message)
            elif any(keyword in msg for keyword in ['doc', '文档', 'readme']):
                work_types['doc'] += 1
                docs.append(commit.message)
            elif any(keyword in msg for keyword in ['test', '测试']):
                work_types['test'] += 1
                tests.append(commit.message)
            elif any(keyword in msg for keyword in ['refactor', '重构', '优化']):
                work_types['refactor'] += 1
                refactors.append(commit.message)
            else:
                work_types['other'] += 1
                others.append(commit.message)
        
        # 生成详细总结
        summary_parts = []
        
        # 开头概述
        summary_parts.append(f"本日共完成{len(commits)}次代码提交，涉及代码变更+{total_insertions}/-{total_deletions}行。")
        
        # 主要技术栈分析
        if file_types:
            main_file_types = sorted(file_types.items(), key=lambda x: x[1], reverse=True)[:3]
            tech_desc = "主要涉及" + "、".join([f"{ext}文件({count}处变更)" for ext, count in main_file_types]) + "的开发工作。"
            summary_parts.append(tech_desc)
        
        # 功能开发详情
        if work_types['feature'] > 0:
            summary_parts.append(f"\n**功能开发方面**：完成了{work_types['feature']}项新功能的开发工作。")
            for i, feature in enumerate(features[:5], 1):  # 显示前5个功能
                feature_desc = self._extract_key_feature(feature)
                summary_parts.append(f"{i}. {feature_desc}")
            if len(features) > 5:
                summary_parts.append(f"以及其他{len(features) - 5}项功能开发。")
        
        # 问题修复详情
        if work_types['fix'] > 0:
            summary_parts.append(f"\n**问题修复方面**：解决了{work_types['fix']}个技术问题。")
            for i, fix in enumerate(fixes[:5], 1):  # 显示前5个修复
                issue_desc = self._extract_key_issue(fix)
                summary_parts.append(f"{i}. {issue_desc}")
            if len(fixes) > 5:
                summary_parts.append(f"以及其他{len(fixes) - 5}个问题的修复。")
        
        # 代码重构详情
        if work_types['refactor'] > 0:
            summary_parts.append(f"\n**代码优化方面**：进行了{work_types['refactor']}项代码重构和优化工作。")
            for i, refactor in enumerate(refactors[:3], 1):  # 显示前3个重构
                refactor_desc = self._extract_key_feature(refactor)  # 重用提取逻辑
                summary_parts.append(f"{i}. {refactor_desc}")
            if len(refactors) > 3:
                summary_parts.append(f"以及其他{len(refactors) - 3}项优化工作。")
        
        # 文档和测试
        if work_types['doc'] > 0:
            summary_parts.append(f"\n**文档完善**：更新和完善了项目文档，共{work_types['doc']}次文档相关提交。")
        
        if work_types['test'] > 0:
            summary_parts.append(f"\n**测试验证**：增加和完善了测试用例，共{work_types['test']}次测试相关提交。")
        
        # 其他工作
        if work_types['other'] > 0:
            summary_parts.append(f"\n**其他开发工作**：完成了{work_types['other']}项其他技术工作。")
            for i, other in enumerate(others[:3], 1):  # 显示前3个其他工作
                other_desc = other.strip()
                summary_parts.append(f"{i}. {other_desc}")
            if len(others) > 3:
                summary_parts.append(f"以及其他{len(others) - 3}项开发任务。")
        
        # 技术影响总结
        if total_insertions > 1000 or total_deletions > 500:
            summary_parts.append(f"\n本日的开发工作涉及大量代码变更，新增{total_insertions}行代码，删除{total_deletions}行代码，体现了较为深入的技术开发和代码重构工作。")
        elif total_insertions > 100:
            summary_parts.append(f"\n通过{total_insertions}行新增代码和{total_deletions}行代码删除，有效推进了项目的技术进展。")
        
        # 确保总结足够详细
        result = "\n".join(summary_parts)
        if len(result) < 300:
            # 如果内容不够300字，添加更多技术细节
            summary_parts.append(f"\n整体而言，本日的开发工作覆盖了项目的多个技术层面，从功能实现到问题解决，从代码优化到质量保证，体现了全面的软件开发实践。这些工作为项目的持续发展和技术债务的解决做出了积极贡献。")
        
        return "\n".join(summary_parts)
    
    def _extract_key_feature(self, commit_msg: str) -> str:
        """提取关键功能描述 - 保留完整内容"""
        # 简化提取逻辑，去掉前缀标记
        msg = commit_msg.strip()
        # 移除常见前缀
        prefixes = ['feat:', 'feature:', '[feat]', '[feature]', '功能:', '新增:', '添加:', 'feat(', 'feature(']
        for prefix in prefixes:
            if msg.lower().startswith(prefix.lower()):
                msg = msg[len(prefix):].strip()
                # 如果是括号形式的前缀，需要找到对应的右括号
                if prefix.endswith('('):
                    close_paren = msg.find(')')
                    if close_paren != -1:
                        msg = msg[close_paren + 1:].strip()
                        if msg.startswith(':'):
                            msg = msg[1:].strip()
                break
        
        # 返回完整内容，不截断
        return msg
    
    def _extract_key_issue(self, commit_msg: str) -> str:
        """提取关键问题描述 - 保留完整内容"""
        msg = commit_msg.strip()
        # 移除常见前缀
        prefixes = ['fix:', 'bug:', '[fix]', '[bug]', '修复:', '问题:', 'fix(', 'bug(']
        for prefix in prefixes:
            if msg.lower().startswith(prefix.lower()):
                msg = msg[len(prefix):].strip()
                # 如果是括号形式的前缀，需要找到对应的右括号
                if prefix.endswith('('):
                    close_paren = msg.find(')')
                    if close_paren != -1:
                        msg = msg[close_paren + 1:].strip()
                        if msg.startswith(':'):
                            msg = msg[1:].strip()
                break
        
        # 返回完整内容，不截断
        return msg

    def format_daily_summary(self, day: int, commits: List[CommitInfo]) -> str:
        """格式化单日提交摘要（保留原有技术格式作为备用）"""
        if not commits:
            return f"{day}日: 无提交记录"

        # 按仓库分组
        repo_commits = defaultdict(list)
        for commit in commits:
            repo_commits[commit.repo_name].append(commit)

        summary_lines = [f"{day}日提交摘要:"]

        total_insertions = sum(c.insertions for c in commits)
        total_deletions = sum(c.deletions for c in commits)
        total_commits = len(commits)

        summary_lines.append(f"  总计: {total_commits}次提交, +{total_insertions}行, -{total_deletions}行")
        summary_lines.append("")

        for repo_name, repo_commits_list in repo_commits.items():
            summary_lines.append(f"  【{repo_name}】:")

            for commit in repo_commits_list:
                time_str = commit.date.strftime("%H:%M")
                files_str = f"({len(commit.files_changed)}个文件)" if commit.files_changed else ""

                # 截断过长的提交消息
                message = commit.message.split('\n')[0]  # 只取第一行
                if len(message) > 60:
                    message = message[:57] + "..."

                summary_lines.append(f"    {time_str} [{commit.commit_hash}] {message} {files_str}")
                summary_lines.append(f"         +{commit.insertions}行 -{commit.deletions}行")

            summary_lines.append("")

        return "\n".join(summary_lines)

    # 月度总结功能已移除 - 根据用户要求不再生成月总结
    # def generate_monthly_work_report(self, year: int, month: int) -> str:
    #     """生成月度技术工作总结报告 - 已废弃"""
    #     pass

    def generate_daily_separate_files(self, year: int, month: int, output_dir: str = "./reports") -> List[str]:
        """为每天生成单独的文件 - 只针对有提交记录的日期"""
        daily_commits = self.collect_monthly_commits(year, month)

        if not daily_commits:
            logger.info(f"{year}年{month}月无提交记录")
            return []

        output_path = Path(output_dir)
        output_path.mkdir(parents=True, exist_ok=True)
        
        generated_files = []

        # 为每一天生成单独的文件
        for day in sorted(daily_commits.keys()):
            commits = daily_commits[day]
            
            # 生成文件名：YYYY-MM-DD_daily_report.md
            date_str = f"{year}-{month:02d}-{day:02d}"
            filename = f"{date_str}_daily_report.md"
            file_path = output_path / filename

            # 生成当日报告内容
            report_content = self._generate_single_day_report(day, commits, year, month)

            # 写入文件
            with open(file_path, 'w', encoding='utf-8') as f:
                f.write(report_content)

            generated_files.append(str(file_path))
            logger.info(f"已生成每日报告: {filename}")

        return generated_files

    def _generate_single_day_report(self, day: int, commits: List[CommitInfo], year: int, month: int) -> str:
        """生成单日报告内容"""
        date_str = f"{year}年{month}月{day}日"
        
        # 每日统计
        day_commits = len(commits)
        day_insertions = sum(c.insertions for c in commits)
        day_deletions = sum(c.deletions for c in commits)
        day_repos = len(set(c.repo_name for c in commits))

        # 报告头部
        report_lines = [
            f"# {date_str} 工作报告",
            f"用户: {self.user_id}",
            f"生成时间: {datetime.now().strftime('%Y-%m-%d %H:%M:%S')}",
            "",
            "## 工作量统计",
            "",
            f"- 提交次数：{day_commits}次",
            f"- 代码变更：+{day_insertions}行 / -{day_deletions}行",
            f"- 涉及项目：{day_repos}个",
            f"- 净增长：{day_insertions - day_deletions}行",
            "",
        ]

        # 使用现有的format_daily_work_summary方法生成详细内容
        daily_work_content = self.format_daily_work_summary(day, commits, year, month)

        # 提取主要工作内容部分（去掉标题和日期）
        content_lines = daily_work_content.split('\n')
        
        # 跳过标题行，从主要工作内容开始
        content_start = 0
        for i, line in enumerate(content_lines):
            if "主要工作内容" in line or "## " in line:
                content_start = i
                break

        if content_start > 0:
            report_lines.extend(content_lines[content_start:])
        else:
            # 如果没找到特定标记，跳过前几行标题
            report_lines.extend(content_lines[3:])

        return "\n".join(report_lines)

    def generate_daily_detailed_reports(self, year: int, month: int) -> str:
        """生成每日详细工作报告 - 这是用户最关键的需求！"""
        daily_commits = self.collect_monthly_commits(year, month)

        if not daily_commits:
            return f"# {year}年{month}月每日工作详情\n\n本月无工作记录。\n"

        # 统计总体数据
        all_commits = []
        for commits in daily_commits.values():
            all_commits.extend(commits)

        total_commits = len(all_commits)
        total_insertions = sum(c.insertions for c in all_commits)
        total_deletions = sum(c.deletions for c in all_commits)
        work_days = len(daily_commits)
        total_repos = len(set(c.repo_name for c in all_commits))

        # 报告头部
        report_lines = [
            f"# {year}年{month}月每日工作详情报告",
            f"用户: {self.user_id}",
            f"生成时间: {datetime.now().strftime('%Y-%m-%d %H:%M:%S')}",
            "",
            "## 月度工作概览",
            "",
            f"本月共工作{work_days}天，完成{total_commits}次代码提交，涉及{total_repos}个项目。",
            f"新增代码{total_insertions}行，删除代码{total_deletions}行，净增长{total_insertions - total_deletions}行。",
            "",
            "## 每日工作详情",
            ""
        ]

        # 按日期排序生成每日详细报告
        for day in sorted(daily_commits.keys()):
            commits = daily_commits[day]

            # 每日标题
            date_str = f"{year}年{month}月{day}日"
            report_lines.append(f"### {date_str}")

            # 每日统计
            day_commits = len(commits)
            day_insertions = sum(c.insertions for c in commits)
            day_deletions = sum(c.deletions for c in commits)
            day_repos = len(set(c.repo_name for c in commits))

            report_lines.append(
                f"**工作量统计**: {day_commits}次提交, +{day_insertions}行, -{day_deletions}行, 涉及{day_repos}个项目")
            report_lines.append("")

            # 使用现有的format_daily_work_summary方法生成详细内容
            daily_work_content = self.format_daily_work_summary(day, commits, year, month)

            # 提取主要工作内容部分（去掉标题）
            content_lines = daily_work_content.split('\n')
            # 跳过标题行，从主要工作内容开始
            content_start = 0
            for i, line in enumerate(content_lines):
                if "主要工作内容" in line:
                    content_start = i
                    break

            if content_start > 0:
                report_lines.extend(content_lines[content_start:])
            else:
                report_lines.extend(content_lines[1:])  # 跳过第一行标题

            report_lines.append("")
            report_lines.append("---")  # 分隔线
            report_lines.append("")

        return "\n".join(report_lines)

    def generate_monthly_report(self, year: int, month: int) -> str:
        """生成月度工作报告（主要接口）- 已改为每日单独文件模式"""
        # 月度总结功能已移除，改为生成每日单独文件
        generated_files = self.generate_daily_separate_files(year, month)
        if not generated_files:
            return f"# {year}年{month}月工作报告\n\n本月无工作记录，未生成任何报告文件。\n"
        
        file_list = "\n".join([f"- {file}" for file in generated_files])
        return f"# {year}年{month}月工作报告\n\n已生成每日单独文件，共 {len(generated_files)} 个文件：\n\n{file_list}\n"


def main():
    """主函数"""
    parser = argparse.ArgumentParser(description='生成Git提交日报')
    parser.add_argument('--year', type=int, default=datetime.now().year, help='年份')
    parser.add_argument('--month', type=int, default=datetime.now().month, help='月份')
    parser.add_argument('--user-id', type=str, help='用户ID（如果不指定，从环境变量读取）')
    parser.add_argument('--source-dir', type=str, help='源代码目录（如果不指定，从环境变量读取）')
    parser.add_argument('--output', type=str, help='输出文件路径（可选）')

    args = parser.parse_args()

    # 从环境变量或参数获取配置
    user_id = args.user_id or os.getenv('DAILY_REPORT_USER_ID')
    source_dir = args.source_dir or os.getenv('DAILY_REPORT_SOURCE_DIR')

    if not user_id:
        logger.error("请指定用户ID（通过--user-id参数或DAILY_REPORT_USER_ID环境变量）")
        sys.exit(1)

    if not source_dir:
        logger.error("请指定源代码目录（通过--source-dir参数或DAILY_REPORT_SOURCE_DIR环境变量）")
        sys.exit(1)

    try:
        generator = DailyReportGenerator(source_dir, user_id)
        report = generator.generate_monthly_report(args.year, args.month)

        if args.output:
            with open(args.output, 'w', encoding='utf-8') as f:
                f.write(report)
            logger.info(f"报告已保存到: {args.output}")
        else:
            print(report)

    except Exception as e:
        logger.error(f"生成报告时出错: {e}")
        sys.exit(1)


if __name__ == "__main__":
    main()
